package lc20240705;
/**
  * @description 买卖股票的最佳时机IV
  * @author 不知名帅哥
  * @date 2024/7/5 9:36
  * @version 1.0
*/
public class MaxProfitKTransactions {
    public int maxProfit(int k, int[] prices) {
        if (prices == null || prices.length == 0 || k == 0) {
            return 0;
        }

        int n = prices.length;

        // 如果 k 大于等于 n / 2，等价于无限次交易
        if (k >= n / 2) {
            int maxProfit = 0;
            for (int i = 1; i < n; i++) {
                if (prices[i] > prices[i - 1]) {
                    maxProfit += prices[i] - prices[i - 1];
                }
            }
            return maxProfit;
        }

        int[][][] dp = new int[n][k + 1][2];

        for (int j = 0; j <= k; j++) {
            dp[0][j][0] = 0;
            dp[0][j][1] = -prices[0];
        }

        for (int i = 1; i < n; i++) {
            for (int j = 1; j <= k; j++) {
                dp[i][j][0] = Math.max(dp[i-1][j][0], dp[i-1][j][1] + prices[i]);
                dp[i][j][1] = Math.max(dp[i-1][j][1], dp[i-1][j-1][0] - prices[i]);
            }
        }

        return dp[n-1][k][0];
    }

    public static void main(String[] args) {
        MaxProfitKTransactions solution = new MaxProfitKTransactions();
        int[] prices = {3,2,6,5,0,3};
        int k = 2;
        int maxProfit = solution.maxProfit(k, prices);
        System.out.println("最大利润是: " + maxProfit); // 输出最大利润
    }
}
